package com.lo.service.impl;

import com.lo.common.JsonResult;
import com.lo.dao.CourseMapper;
import com.lo.dao.OptionScoreMapper;
import com.lo.dao.TextualMaterialMapper;
import com.lo.dao.UserRateMapper;
import com.lo.entity.CourseWithTCHName;
import com.lo.entity.UserRate;
import com.lo.service.RecommendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RecommendServiceImpl implements RecommendService {
    @Autowired
    UserRateMapper userRateMapper;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    TextualMaterialMapper textualMaterialMapper;
    @Autowired
    OptionScoreMapper optionScoreMapper;
    /*
     * @description: 推荐算法
     * @param id:用户id
     * @return com.lo.common.JsonResult
     * @author: ZijianZhao
     * @date: 2024/3/13 15:50
     */
    @Override
    public JsonResult selectRecommendation(Long id) {

//        System.out.println(getRatingMap());
//        System.out.println("推荐测试点2");

        Map<String, Map<String, Double>> ratings = getRatingMap();
//        System.out.println("retings:"+ratings);
        // 创建协同过滤对象
        UserBasedCollaborativeFiltering filter = new UserBasedCollaborativeFiltering(ratings);

        // 为指定用户推荐物品
        String targetUser = id.toString();
        if(ratings.get(targetUser)==null){
            //该用户没有进行任何的打分
            List<UserRate> bestCourseId=userRateMapper.getBestCourse();
            List<String>bestCourseName=new ArrayList<>();
            for(UserRate i:bestCourseId){
                bestCourseName.add(courseMapper.selectCourseById(i.getCourseid()).get(0).getName());
            }
            System.out.println("bestCourseName:"+bestCourseName);
            List<CourseWithTCHName> result = PackCourseOrText(bestCourseName);
            return new JsonResult(0,"推荐课程",result);
        }
        int numRecommendations = optionScoreMapper.GetRecNum();//指定多少个邻居
//        System.out.println("numRecommendations:"+numRecommendations);
        List<String> recommendations = filter.recommendItems(targetUser, numRecommendations);
        List<String> randomCourse=new ArrayList<>();
        // 输出推荐结果
        System.out.println("recommendations:"+recommendations);
        if(recommendations.size()==0)
        {
//            System.out.println("这个人对所有商品都打了分");
        } else if (recommendations.size()<=4) {
            randomCourse=recommendations;
        } else if(recommendations.size()>4){
            System.out.println("size out of 4");
            Map<Integer,String> map = new HashMap<>();
            Random random = new Random();
            while (map.size()<4){
                Integer index = random.nextInt(Integer.valueOf(recommendations.size()));
                if (!map.containsKey(index)){
                    map.put(index,"");
                    randomCourse.add(recommendations.get(index));
                }
            }
        }
//        targetUser
//        System.out.println("推荐测试点3:"+recommendations);
        System.out.println("randomCourse:"+randomCourse);
        List<CourseWithTCHName> result = PackCourseOrText(randomCourse);
        System.out.println("推荐结果 "+result);
        return new JsonResult(0,"推荐课程",result);
    }



    /***
     * 根据用户id组建Map<String,Double>
     * @param userId
     * @return 用户对所有商品的打分map
     */
    public Map<String,Double> getUserMap(Long userId){
        Map<String,Double> result=new HashMap<>();
//        System.out.println("u:"+userId);
//        System.out.println("selectByUserId"+userRateMapper.selectByUserId(userId));
        List<UserRate>userRateList=userRateMapper.selectByUserId(userId);

        for(UserRate u:userRateList){
            result.put(u.getCourse().getName(),u.getRate()<0.00001?0.00001:u.getRate());
        }
        return result;
    }

    /**
     * 根据视频名称查询，构建CourseWithTCHName视图
     * @param recommendations
     * @return CourseWithTCHName视图
     */
    List<CourseWithTCHName> PackCourseOrText(List<String> recommendations) {
        List<CourseWithTCHName> result=new ArrayList<>();

        for(String name : recommendations){
            List<CourseWithTCHName> search = courseMapper.selectByName(name);
            if(search.isEmpty()){
                continue;
            }
            else
                result.add(search.get(0));//对于重名的课程，只返回第一次查到的课程
        }
        return result;
    }
    /**
     * 根据Userrate表返回所有用户的打分情况，构成一个大的map
     * @return
     */
    public Map<String,Map<String,Double>> getRatingMap(){
        Map<String,Map<String,Double>> result=new HashMap<>();

        List<UserRate>userRateList=userRateMapper.selectALl();
        Map<Long,Boolean> names=new HashMap<>();
        for(UserRate u : userRateList)
        {
            names.put(u.getUserid(),true);
        }
        System.out.println("names:"+names);
        for(Long i : names.keySet()){
//            System.out.println("i:"+i);
            result.put(i.toString(),getUserMap(i));
        }
        return result;
    }
//    @Override
//    public JsonResult updateUserRatings(Long userId, Long courseId, double rate) {
//        UserRate ur=userRateMapper.selectById(userId).get(0);
//        Map<String, Double> map = new HashMap<>();
//        map= (Map)JSON.parse(ur.getRatings());
//
//        Long x=Long.valueOf(courseId);
//        List<Course> Lc = courseMapper.selectCourseById(x);
//
//        if(Lc.size()==0){
//            return new JsonResult<>(201,"未查找到课程:"+courseId,null);
//        }
//        else {
//            Course c = Lc.get(0);
//            map.put(c.getName(), rate);//put方法，当存在该键值对时修改值，不存在则新增
//            ur.setRatings(JSONArray.toJSONString(map));
//            userRateMapper.updateUserRate(ur);
//            System.out.println(ur);
//            System.out.println("Map格式输出：" + map);
//            return new JsonResult<>(201, "查找到课程:", map);
//        }
//    }
//
//    @Override
//    public JsonResult selectUserRatesById(Long userId) {
//        return new JsonResult<>(200,"查找用户",userRateMapper.selectById(userId).get(0));
//    }
//
//    @Override
//    public JsonResult LikeCourse(Long userId, Long courseId) {
//
//        return new JsonResult<>(0,"点赞成功"+userId,userRateMapper.updateUserRate(userRate));
//    }
//
//    @Override
//    public JsonResult UnLikeCourse(Long userId, Long courseId) {
//        List<Course> coursesList=courseMapper.selectCourseById(courseId);
//        if(coursesList.size()==0){
//            return new JsonResult<>(400,"商品不存在:"+courseId,null);
//        }
//        List<UserRate> userRateList=userRateMapper.selectById(userId);
//        if(userRateList.size()==0){
//            return new JsonResult<>(400,"用户不存在于rate表中，请联系管理员:"+userId,null);
//        }
//
//        UserRate userRate = userRateList.get(0);
//        Course course = coursesList.get(0);
//
//        //获取用户点赞列表
//        String Json_likelist = userRate.getLikelist();
//        String Json_Rating = userRate.getRatings();
//        //String转化成map
//        Map<String,Long> likeMap = new HashMap<>();
//        Map<String,Double> RatingMap = new HashMap<>();
//        likeMap = (Map)JSON.parse(Json_likelist);
//        RatingMap = (Map<String,Double>)JSON.parseObject(Json_Rating,Map.class);
//        //将本课程id加入map中
//        System.out.println("likeMap:"+ likeMap);
//        System.out.println(courseId.getClass());
//        System.out.println(likeMap.getClass());
//
////        likeMap.put(courseId.toString(),userId);
//        likeMap.remove(courseId.toString());
//
//
//        if(!RatingMap.containsKey(course.getName()))
//            RatingMap.put(course.getName(),10.0);
//        else {
//            Object d = RatingMap.get(course.getName());
//            double db = ((BigDecimal) d).doubleValue();
//            RatingMap.put(course.getName(), db - 10.0);//取消点赞-10分
//        }
//        //map转换回String
//        String newList = JSONArray.toJSON(likeMap).toString();
//        String newRating = JSONArray.toJSON(RatingMap).toString();
//        userRate.setLikelist(newList);
//        userRate.setRatings(newRating);
//        System.out.println("userRate:"+userRate);
//        return new JsonResult<>(0,"点赞成功"+userId,userRateMapper.updateUserRate(userRate));
//    }
//
//    @Override
//    public JsonResult addUserRate(Long userId) {
//        UserRate userRate=new UserRate();
//        userRate.setId(userId);
//        userRate.setRatings("{}");//注意ratings中必须至少有{}才能被转换成map
//        userRate.setGroup("defult");
//        return new JsonResult(200,"尝试添加用户"+userId+"的空白评分",userRateMapper.insert(userRate));
//    }
    @Override
    public JsonResult deleteUserAllRateById(Long userid, Long courseid) {

        return new JsonResult<>(200,"删除用户"+ userid,userRateMapper.delete(userid,courseid));
    }

    @Override
    public JsonResult update(Long userId, Long courseId, int option) {
        List<UserRate> userRateList=userRateMapper.selectBy2Id(userId,courseId);
        UserRate userRate;

        if(userRateList.size()==0){
            userRate=new UserRate(userId,courseId);
            userRate.setId(userRateMapper.insert(userRate));
        }
        else {
            userRate=userRateList.get(0);
//            System.out.println("userRate："+userRate);
        }
        JsonResult result=new JsonResult<>(404,"操作符不存在",userRate);
        switch (option) {
            case 1:
                //点赞操作
                userRate.setIslike(userRate.getIslike()==0?1:0);
                userRate.setRate(userRate.getRate()+(userRate.getIslike()==0?10:-10));
                result = new JsonResult<>(0,userRate.getIslike()==1?"点赞成功":"取消点赞",userRate);
                break;
            case 2:
                //收藏操作
                break;
        }
        userRateMapper.updateUserRate(userRate);

        return result;
    }

    @Override
    public JsonResult getLike(Long userId, Long courseId) {
        List<UserRate> userRateList=userRateMapper.selectBy2Id(userId,courseId);
        UserRate userRate;
//        System.out.println("userRateList"+userRateList);
        if(userRateList.size()==0){
            userRate=new UserRate(userId,courseId);
            userRate.setId(userRateMapper.insert(userRate));
        }
        else {
            userRate=userRateList.get(0);
//            System.out.println("userRate："+userRate);
        }
        JsonResult result=new JsonResult<>(0,userRateList.size()!=0?"评分表已存在":"评分表已添加",userRate);

        return result;
    }


}
